Page({
  data: {
    shopId: '',
    articles: [],
    loading: true
  },

  onLoad(options) {
    if (options.shopId) {
      this.setData({ shopId: options.shopId })
      this.loadArticles(options.shopId)
    }
  },

  async loadArticles(shopId) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('articles')
        .where({ shopId })
        .orderBy('createTime', 'desc')
        .get()
      
      // 处理文章数据
      const formattedArticles = data.map(article => ({
        ...article,
        description: article.content.substring(0, 100) + '...', // 截取前100个字符作为描述
        createTime: this.formatTime(article.createTime) // 格式化时间
      }))
      
      this.setData({ 
        articles: formattedArticles,
        loading: false
      })
    } catch (error) {
      console.error('加载文章列表失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date

    // 如果是今天
    if (diff < 24 * 60 * 60 * 1000) {
      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `今天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }

    // 如果是昨天
    if (diff < 48 * 60 * 60 * 1000) {
      return '昨天'
    }

    // 如果是今年
    if (date.getFullYear() === now.getFullYear()) {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }

    // 其他情况
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  },

  viewArticle(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/articles/detail?id=${id}&shopId=${this.data.shopId}`
    })
  }
}) 